package com.dlyk.service.impl;

import com.dlyk.bean.TPermission;
import com.dlyk.bean.TRole;
import com.dlyk.bean.TUser;
import com.dlyk.constant.Constants;
import com.dlyk.manager.RedisManager;
import com.dlyk.mapper.TPermissionMapper;
import com.dlyk.mapper.TRoleMapper;
import com.dlyk.mapper.TUserMapper;
import com.dlyk.query.BaseQuery;
import com.dlyk.query.UserQuery;
import com.dlyk.service.UserService;
import com.dlyk.utils.CacheUtils;
import com.dlyk.utils.JWTUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.annotation.Resources;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 用户实现类
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private TUserMapper tUserMapper;

    // 密码加密器
    @Autowired
    private PasswordEncoder passwordEncoder;

    // 角色
    @Autowired
    private TRoleMapper tRoleMapper;

    @Resource
    private RedisManager redisManager;

    @Resource
    private TPermissionMapper tPermissionMapper;

    /**
     * 登录用户安全验证
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tUser=tUserMapper.selectByUsername(username);
        if (tUser==null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        // 查询当前用户的角色
        List<TRole> tRolesList = tRoleMapper.selectByUserId(tUser.getId());
        // 字符串的角色列表
        List<String> stringRoleList = new ArrayList<>();
        tRolesList.forEach((tRole) -> {
            stringRoleList.add(tRole.getRole());
        });
        // 设置用户角色
        tUser.setRoleList(stringRoleList);

        // 查询当前用户的菜单权限
        List<TPermission> permissionList=tPermissionMapper.selectMenuPermissionByUserId(tUser.getId());
        tUser.setMenuPermissionList(permissionList);

        // 查询当前用户的功能权限
        List<TPermission> buttonPermissionList=tPermissionMapper.selectPermissionByUserId(tUser.getId());
        List<String> stringPermissionList=new ArrayList<>();
        buttonPermissionList.forEach(buttonPermission->{
            stringPermissionList.add(buttonPermission.getCode());
        });
        tUser.setPermissionList(stringPermissionList);
        return tUser;
    }

    /**
     * 用户分页查询
     * @param current
     */
    @Override
    public PageInfo<TUser> getUserByPage(Integer current) {
        // 设置PageHepler
        PageHelper.startPage(current, Constants.PAGE_SIZE);
        // 查询
         List<TUser> list=tUserMapper.selectByUserPage(BaseQuery.builder().build());
        // 封装分页数据
        PageInfo<TUser> info=new PageInfo<>(list);
        return info;
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @Override
    public TUser getUserById(Integer id) {
        TUser tUser = tUserMapper.selectDetailById(id);
        return tUser;
    }

    /**
     * 新增用户
     * @param userQuery
     * @return
     */
    @Override
    public int saveUser(UserQuery userQuery) {
        TUser tUser = new TUser();
        BeanUtils.copyProperties(userQuery,tUser);
        tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));  // 密码加密
        tUser.setCreateTime(new Date());  // 创建时间
        Integer userId = JWTUtils.parseUserFromJWT(userQuery.getToken()).getId();
        tUser.setCreateBy(userId);  // 创建人

        return tUserMapper.insertSelective(tUser);
    }

    /**
     * 更新用户信息
     * @param userQuery
     * @return
     */
    @Override
    public int updateUser(UserQuery userQuery) {
        TUser tUser = new TUser();
        BeanUtils.copyProperties(userQuery,tUser);

        // 如果有密码，进行密码加密
        if (StringUtils.hasText(userQuery.getLoginPwd())){
            tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));  // 密码加密
        }

        tUser.setEditTime(new Date());  // 编辑时间
        Integer userId = JWTUtils.parseUserFromJWT(userQuery.getToken()).getId();
        tUser.setEditBy(userId);  // 创建人

        return tUserMapper.updateByPrimaryKeySelective(tUser);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @Override
    public Integer deleteUser(Integer id) {
        return tUserMapper.deleteByPrimaryKey(id);
    }

    /**
     * 批量删除用户
     * @param list
     * @return
     */
    @Override
    public int batchDelUser(List<String> list) {
        return tUserMapper.batchDelUser(list);
    }

    /**
     * 查询负责人
     * @return
     */
    @Override
    public List<TUser> selectOwner() {
        // 获取数据
        return CacheUtils.getCacheData(()->{
            // 从redis查询数据
            return (List<TUser>) redisManager.getValue(Constants.REDIS_OWNER_KEY);
        },()->{
            // 从数据库查询数据
            return tUserMapper.selectOwner();
        },(t)->{
            // 将数据放入redis缓存
            redisManager.setValue(Constants.REDIS_OWNER_KEY,t);
        });
    }
}
